import React, { useMemo, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import './style/Car.css'
import { ischecked, checkAll, del, addNum, delNum } from '../store/modules/cart'
import { useNavigate } from 'react-router-dom'
import { Checkbox, SubmitBar, Empty, Card, Stepper, Toast } from 'react-vant'
import { ArrowLeft, Edit, Success, Delete } from '@react-vant/icons'

interface CartItem {
  id: number
  title: string
  content: string
  price: number
  num: number
  image: string
  flag: boolean
}

export default function Car() {
  const cart = useSelector((state: { cart: CartItem[] }) => state.cart)
  const navigate = useNavigate()
  const dispatch = useDispatch()
  const [isEditMode, setIsEditMode] = useState(false)
  const [selectedItems, setSelectedItems] = useState<number[]>([])

  const handleCheck = (value: boolean, item: CartItem) => {
    if (value) {
      setSelectedItems([...selectedItems, item.id])
    } else {
      setSelectedItems(selectedItems.filter(id => id !== item.id))
    }
    dispatch(ischecked({ id: item.id, checked: value }))
  }

  const isAllChecked = useMemo(() => {
    return cart.length >= 1 ? cart.every(item => item.flag) : false
  }, [cart])

  const handleCheckAll = (value: boolean) => {
    dispatch(checkAll(value))
    if (value) {
      setSelectedItems(cart.map(item => item.id))
    } else {
      setSelectedItems([])
    }
  }

  const handleQuantityChange = (value: number, item: CartItem) => {
    if (value > item.num) {
      dispatch(addNum({ id: item.id }))
    } else {
      dispatch(delNum({ id: item.id }))
    }
  }

  const handleSubmit = () => {
    if (isEditMode) {
      if (selectedItems.length === 0) {
        Toast('请选择要删除的商品')
        return
      }
      dispatch(del(selectedItems))
      setSelectedItems([])
      setIsEditMode(false)
    } else {
      const selectedCartItems = cart.filter(item => item.flag)
      if (selectedCartItems.length === 0) {
        Toast('请选择要结算的商品')
        return
      }
      navigate('/order', { state: selectedCartItems })
    }
  }

  const totalPrice = useMemo(() => {
    return cart.filter(item => item.flag).reduce((total, item) => {
      return total + item.price * item.num
    }, 0)
  }, [cart])

  return (
    <div className="cart-page">
      <div className="cart-header">
        <ArrowLeft onClick={() => navigate('/app/shou')} />
        <h2>购物车</h2>
        {isEditMode ? (
          <Success onClick={() => setIsEditMode(false)} />
        ) : (
          <Edit onClick={() => setIsEditMode(true)} />
        )}
      </div>

      {cart.length === 0 ? (
        <Empty description="购物车是空的" />
      ) : (
        <div className="cart-content">
          {cart.map((item) => (
            <Card key={item.id} className="cart-item">
              <div className="item-main">
                <Checkbox
                  checked={item.flag}
                  onChange={(value) => handleCheck(value, item)}
                />
                <div className="item-image">
                  <img src={item.image} alt={item.name} />
                </div>
                <div className="item-info">
                  <h3 className="item-title">{item.name}</h3>
                  <p className="item-desc">{item.description}</p>
                  <div className="item-price">¥{(item.price / 10).toFixed(2)}</div>
                </div>
              </div>
              <div className="item-footer">
                <Stepper
                  value={item.num}
                  min={1}
                  onChange={(value) => handleQuantityChange(value, item)}
                  theme="round"
                  buttonSize="22"
                  disableInput
                />
              </div>
            </Card>
          ))}
        </div>
      )}

      <SubmitBar
        price={totalPrice * 10}
        buttonText={isEditMode ? '删除商品' : '提交订单'}
        disabled={isEditMode ? selectedItems.length === 0 : cart.filter(item => item.flag).length === 0}
        onSubmit={handleSubmit}
        className="cart-submit"
      >
        <Checkbox checked={isAllChecked} onChange={handleCheckAll}>
          全选
        </Checkbox>
      </SubmitBar>
    </div>
  )
}
